package br.univas.dao;

import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.index.Index;

import br.edu.univas.locadoragraphtcc.database.Connection;
import br.univas.to.UserTO;


public class UserDAO {
	private static final String INDEXKEY = "user";
	private static final String USERKEY = "login";
	private Connection conn;

	public UserDAO() {
		conn = Connection.getInstance();
	}

	public boolean veryfyUserLogin(UserTO user) {
		long start = System.currentTimeMillis();
		GraphDatabaseService graph = conn.newGraphDatabase();

		Index<Node> index = graph.index().forNodes(INDEXKEY);

		Node node = index.get(USERKEY, user.getEmail().toLowerCase()).getSingle();
		if (node == null) {
			System.out.println("Usuario não existe");
			graph.shutdown();
			double total = System.currentTimeMillis() - start;
			System.out.println("Time: " + total/1000);
			return false;
		}
		graph.shutdown();
		System.out.println("Usuario existe");
		double total = System.currentTimeMillis() - start;
		System.out.println("Time: " + total/1000);
		return true;
	}

	public boolean saveUserGraph(UserTO user) {
		long start = System.currentTimeMillis();
		GraphDatabaseService graph = conn.newGraphDatabase();
		Index<Node> index = graph.index().forNodes(INDEXKEY);
		Node node = index.get(USERKEY, user.getEmail().toLowerCase()).getSingle();

		if (node == null) {
			System.out.println("Inserindo usuario");
			Transaction tx = graph.beginTx();
			try {
				node = graph.createNode();
				node.setProperty(USERKEY, user.getEmail().toLowerCase());
				node.setProperty("name", user.getName().toLowerCase());
				node.setProperty("password", user.getPassword().toLowerCase());

				index.add(node, USERKEY, user.getEmail().toLowerCase());
				tx.success();
			} catch (Exception e) {
				tx.failure();
			} finally {
				tx.finish();
			}
			double total = System.currentTimeMillis() - start;
			System.out.println("Time: " + total / 1000);
			System.out.println("Usuario cadastrado com sucesso");
			graph.shutdown();
			return true;
		}
		graph.shutdown();
		double total = System.currentTimeMillis() - start;
		System.out.println("Time: " + total/1000);
		return false;

	}

}